#!/bin/sh

MYSQLDUMP=`which mysqldump`
if [ ! -f $MYSQLDUMP ]
then
	echo "mysqldump binary not found"
	exit 1
fi

SVN=`which svn`
if [ ! -f $SVN ]
then
	echo "svn binary not found"
	exit 1
fi

# Make relative path to dump file work when script is not called from within ./db
SCRIPTPATH=`dirname "$0"`
cd "$SCRIPTPATH"
echo "Switched to directory $SCRIPTPATH (check: `pwd`)"

DATE=`date +"%F %H:%M"`
DB="visualpun"
DBUSER="visualpun"
DBPASS="sdf09umXu"
DUMPFILE="visualpun-auto-dump.sql"
LOGFILE="visualpun-dump.log"
USER=`whoami`




if [ "$1" != "" ]
then
    echo "Using $1 as basename for dump"
    USER="$1"
fi


echo "Dumping database $DB to $DUMPFILE"


$MYSQLDUMP --databases --ignore-table=$DB.cache_menu --ignore-table=$DB.cache_form  -u "$DBUSER" -p$DBPASS  "$DB" > "$DUMPFILE"

# Special tables
echo "-- Structure only for voluminous cache tables" >> $DUMPFILE
$MYSQLDUMP --no-data -u "$DBUSER" -p$DBPASS "$DB" cache_menu cache_form >> $DUMPFILE

#DUMPSIZE=`df -k $DUMPFILE`
#DUMPSIZE=`stat -c%s $DUMPFILE`
DUMPSIZE=`ls -al $DUMPFILE | awk '{ print $5 }'`
echo "Dump size is $DUMPSIZE Bytes"

if [ $DUMPSIZE -lt 1024 ]
then
	echo "Dump considered to small ($DUMPSIZE Bytes)"
	exit 1
fi


#Uploading dump to repository"
$SVN up "$DUMPFILE"
$SVN ci -m "Database snapshot" "$DUMPFILE"
REV=`$SVN info $DUMPFILE | grep Revision | cut -d: -f2`

#add new line to logfile
$SVN up "$LOGFILE"
echo "$DATE $REV $USER" >> $LOGFILE
$SVN ci -m "Database snapshot logfile" "$LOGFILE"

exit 0
